package com.dmall.content.service.impl;

import com.dmall.content.mapper.ContentCategoryMapper;
import com.dmall.content.pojo.TbContentCategory;
import com.dmall.content.service.ContentCategoryService;
import com.dmall.framework.result.DmallResult;
import com.dmall.utils.EasyUITreeNodeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 内容分类管理Service
 * @author Chen 2017/10/22
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
    @Autowired
    private ContentCategoryMapper contentCategoryMapper;
    /**
     * 获取分类列表
     * @param ParentId
     * @return
     */
    @Override
    public List<EasyUITreeNodeInfo> getContentCatList(Long ParentId) {
        //根据parentid查询子节点列表
        Example example = new Example(TbContentCategory.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId",ParentId);
        List<TbContentCategory> entities = contentCategoryMapper.selectByExample(example);
        //转换成erayUI treeNode
        List<EasyUITreeNodeInfo> infos = new ArrayList<>();
        for(TbContentCategory entity :entities){
            EasyUITreeNodeInfo info = new EasyUITreeNodeInfo();
            info.setId(entity.getId());
            info.setText(entity.getName());
            info.setState(entity.getIsParent()?"closed":"open");
            infos.add(info);
        }
        return infos;
    }
    /**
     * 添加一个类型
     */
    @Override
    public DmallResult addContentCategory(Long parentId, String name) {
        TbContentCategory category = new TbContentCategory();
        category.setParentId(parentId);
        category.setName(name);
        //1正常，2删除
        category.setStatus(1);
        category.setSortOrder(1);
        category.setIsParent(false);//新添加的节点是叶子节点
        category.setUpdated(new Date());
        category.setCreated(new Date());
        int id = contentCategoryMapper.insert(category);
        //判断父节点isparent属性，如果不是true 改为true
        TbContentCategory parent = contentCategoryMapper.selectByPrimaryKey(parentId);
        if(!parent.getIsParent()){
            parent.setIsParent(true);
            contentCategoryMapper.updateByPrimaryKey(parent);
        }
        return DmallResult.ok(category);
    }
}
